package com.example.demo.controller;

import com.example.demo.common.Result;
import com.example.demo.dto.UserQueryDTO;
import com.example.demo.param.LoginParam;
import com.example.demo.param.UserUpdateParam;
import com.example.demo.service.AdminService;
import com.example.demo.vo.LoginVO;
import com.example.demo.vo.UserVO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;

/**
 * 管理员控制器
 * 
 * @author zhang
 * @date 2024
 */
@RestController
@RequestMapping("/api/admin")
public class AdminController {
    
    private static final Logger logger = LoggerFactory.getLogger(AdminController.class);
    
    @Autowired
    private AdminService adminService;
    
    /**
     * 管理员登录
     */
    @PostMapping("/login")
    public Result<LoginVO> login(@Valid @RequestBody LoginParam param) {
        try {
            logger.info("管理员登录: {}", param.getUsername());
            LoginVO vo = adminService.login(param.getUsername(), param.getPassword());
            return Result.create(vo);
        } catch (Exception e) {
            logger.error("管理员登录失败: {}", e);
            return Result.create().error(401, e.getMessage());
        }
    }
    
    /**
     * 查询用户列表
     */
    @PostMapping("/users/list")
    public Result<List<UserVO>> queryUsers(@Valid @RequestBody UserQueryDTO dto) {
        try {
            logger.info("查询用户列表: {}", dto.getUsername());
            
            // 计算分页参数
            if (dto.getPageNum() == null || dto.getPageNum() <= 0) {
                dto.setPageNum(1);
            }
            if (dto.getPageSize() == null || dto.getPageSize() <= 0) {
                dto.setPageSize(10);
            }
            
            int pageNum = dto.getPageNum();
            int pageSize = dto.getPageSize();
            
            List<UserVO> users = adminService.queryUsers(dto);
            long total = adminService.countUsers(dto);
            
            // 计算总页数
            int totalPages = (int) Math.ceil((double) total / pageSize);
            
            Result<List<UserVO>> result = Result.create(users);
            result.setTotal(total);
            result.setPageNum(pageNum);
            result.setPageSize(pageSize);
            result.setTotalPages(totalPages);
            
            return result;
        } catch (Exception e) {
            logger.error("查询用户列表失败: {}", e.getMessage());
            return Result.create().error(500, e.getMessage());
        }
    }
    
    /**
     * 更新用户信息
     */
    @PostMapping("/users/update")
    public Result<Void> updateUser(@RequestParam Long id, @Valid @RequestBody UserUpdateParam param) {
        try {
            logger.info("更新用户信息: userId={}", id);
            param.setId(id);
            adminService.updateUser(param);
            return Result.create(null);
        } catch (Exception e) {
            logger.error("更新用户信息失败: {}", e.getMessage());
            return Result.create().error(400, e.getMessage());
        }
    }
    
    /**
     * 禁用用户
     */
    @PostMapping("/users/disable")
    public Result<Void> disableUser(@RequestParam Long id) {
        try {
            logger.info("禁用用户: userId={}", id);
            UserUpdateParam param = new UserUpdateParam();
            param.setId(id);
            param.setStatus(0);
            adminService.updateUser(param);
            return Result.create(null);
        } catch (Exception e) {
            logger.error("禁用用户失败: {}", e.getMessage());
            return Result.create().error(400, e.getMessage());
        }
    }
    
    /**
     * 启用用户
     */
    @PostMapping("/users/enable")
    public Result<Void> enableUser(@RequestParam Long id) {
        try {
            logger.info("启用用户: userId={}", id);
            UserUpdateParam param = new UserUpdateParam();
            param.setId(id);
            param.setStatus(1);
            adminService.updateUser(param);
            return Result.create(null);
        } catch (Exception e) {
            logger.error("启用用户失败: {}", e.getMessage());
            return Result.create().error(400, e.getMessage());
        }
    }
}

